//
//  ByHomeIndexVC.m
//  mijifen_ios
//
//  Created by 朱凯 on 2017/10/20.
//  Copyright © 2017年 itboye. All rights reserved.
//

#import "ByHomeIndexVC.h"

// vc
#import "ByLocationCityVC.h"                // 定位界面
#import "ByShopVC.h"                        // 商城
#import "ByShopProductDetailVC.h"           // 商品详情
#import "ByGetScoreFromPayMoreVC.h"         // 消费得积分-更多
#import "ByServiceGoodMoreVC.h"             // 服务更优惠-更多
#import "ByRedPacketComeInMoreVC.h"         // 红包-更多

// view
#import "ByViewHomeIndexHeader.h"           // 头视图
#import "ByViewHomeIndexCity.h"             // 城市视图
#import "ByViewHomeIndexSectionHeader.h"    // 组头视图
#import "ByViewRedPacketComeInfomation.h"   // 红包详情

// cell
#import "ByCellHomeIndexClassPart.h"        // 分类板块cell
#import "ByCellHomeIndexTextAD.h"           // 文本广告
#import "ByCellGetScoreFromPay.h"           // 消费得积分
#import "ByCellServiceGood.h"               // 服务更实惠
#import "ByCellRedPacketComeIn.h"           // 红包席卷而来
#import "ByCellShopProduct.h"               // 商品


@interface ByHomeIndexVC () <UITableViewDelegate, UITableViewDataSource>


@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) ByViewHomeIndexHeader *header;
@property (nonatomic, strong) ByViewHomeIndexCity *cityView;

@end

@implementation ByHomeIndexVC
{
    CGFloat _naviBarAlpha;      // 导航栏透明度
}

#pragma mark - view method
- (void)viewDidLoad {
    [super viewDidLoad];

    _naviBarAlpha = 0;
    
    [self addCustomItemviews:@[self.cityView] position:ByNavigationItemPositionModeLeft];
    
    // 创建视图
    [self createTableView];
    
    // 添加通知
    [self addNotification];

    // 模拟一个通知事件，但不通知其他注册该通知名的控制器
    NSNotification *noti = [NSNotification notificationWithName:KLoginStatusChangeNotificationName object:nil userInfo:@{KLoginStatusChangeNotificationStatusKey : @(USER != nil)}];
    [self loginStatusChange:noti];
    
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self setNaviAttributeWithTranslucent:true stateBarLightContent:true];
    
    // 设置导航栏的透明度变化
    UIColor *color = [BY_THEME_COLOR colorWithAlphaComponent:_naviBarAlpha];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:color] forBarMetrics:UIBarMetricsDefault];
    
}
- (void)viewSafeAreaInsetsDidChange {
    
    [super viewSafeAreaInsetsDidChange];
    
    // 为了美观，我们保持header的内容区域为100，其他的部分是导航栏部分（即view的安全区域）
    self.header.height = self.view.safeAreaInsets.top + 100;
}

#pragma mark - 通知事件
// 移除通知
- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 添加通知
- (void)addNotification {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginStatusChange:) name:KLoginStatusChangeNotificationName object:nil];
}
// 登录状态改变
- (void)loginStatusChange:(NSNotification *)noti {

    BOOL isLogin = [noti.userInfo[KLoginStatusChangeNotificationStatusKey] boolValue];

    NSArray *rightItems = isLogin ? @[@"消息"] : @[@"登录"];

    // 设置导航栏item
    [self addBYItemviews:rightItems mode:ByNavigationItemModeImageAndText position:ByNavigationItemPositionModeRight];
}

#pragma mark - 懒加载
- (ByViewHomeIndexCity *)cityView {
    
    if (!_cityView) {
        _cityView = [[ByViewHomeIndexCity alloc] initWithFrame:CGRectMake(0, 0, 0, 44)];
        _cityView.city = @"定位";
        [_cityView addTarget:self action:@selector(cityLocation) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cityView;
}

#pragma mark - 创建视图
- (void)createTableView {
    
    self.table = [[UITableView alloc] init];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.backgroundColor = BY_BG_COLOR;
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 49, 0)).priorityMedium();
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-49);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        }
    }];
    
    self.header = [[ByViewHomeIndexHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 0)];
    self.table.tableHeaderView = self.header;
    
    [self.table registerClass:[ByCellHomeIndexClassPart class] forCellReuseIdentifier:@"classPartCell"];
    [self.table registerClass:[ByCellHomeIndexTextAD class] forCellReuseIdentifier:@"textADCell"];
    [self.table registerClass:[ByCellGetScoreFromPay class] forCellReuseIdentifier:@"getScoreCell"];
    [self.table registerClass:[ByCellServiceGood class] forCellReuseIdentifier:@"serviceCell"];
    [self.table registerClass:[ByCellRedPacketComeIn class] forCellReuseIdentifier:@"redPacketCell"];
    [self.table registerClass:[ByCellShopProduct class] forCellReuseIdentifier:@"productCell"];

    [self.table registerClass:[ByViewHomeIndexSectionHeader class] forHeaderFooterViewReuseIdentifier:@"sectionHeader"];
    

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 6;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            // 分类板块
            return 1;
            break;
        case 1:
            // 文字广告
            return 1;
            break;
        case 2:
            // 消费得积分
            return 1;
            break;
        case 3:
            // 服务更实惠
            return 1;
            break;
        case 4:
            // 红包席卷而来
            return 1;
            break;
        case 5:
            // 商品推荐
            return 3;
            break;
        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 分类板块
    if (indexPath.section == 0) {
        
        ByCellHomeIndexClassPart *cell = [tableView dequeueReusableCellWithIdentifier:@"classPartCell"];
        cell.didSelectPart = ^(NSInteger index) {
            [self touchClassPart:index];
        };
        
        return cell;
    }
    // 文本广告
    else if (indexPath.section == 1) {
        
        ByCellHomeIndexTextAD *cell = [tableView dequeueReusableCellWithIdentifier:@"textADCell"];
        
        return cell;
    }
    // 消费得积分
    else if (indexPath.section == 2) {
        
        ByCellGetScoreFromPay *cell = [tableView dequeueReusableCellWithIdentifier:@"getScoreCell"];
        return cell;
    }
    // 服务更实惠
    else if (indexPath.section == 3) {

        ByCellServiceGood *cell = [tableView dequeueReusableCellWithIdentifier:@"serviceCell"];
        
        return cell;
    }
    // 红包
    else if (indexPath.section == 4) {
        
        ByCellRedPacketComeIn *cell = [tableView dequeueReusableCellWithIdentifier:@"redPacketCell"];
        
        return cell;
    }
    // 商品
    else if (indexPath.section == 5) {
        
        ByCellShopProduct *cell = [tableView dequeueReusableCellWithIdentifier:@"productCell"];
        
        return cell;
    }
    
    return [UITableViewCell new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 分类板块
    if (indexPath.section == 0) {
        return SCREEN_WIDTH / 5 * 2 + 20;
    }
    // 文字广告
    else if (indexPath.section == 1) {
        return 40;
    }
    // 消费
    else if (indexPath.section == 2) {
        
        return (SCREEN_WIDTH - 1 * 2) / 3;
    }
    // 服务
    else if (indexPath.section == 3) {
        return [tableView fd_heightForCellWithIdentifier:@"serviceCell" configuration:^(id cell) {
            
        }];
    }
    // 红包
    else if (indexPath.section == 4) {
        return [tableView fd_heightForCellWithIdentifier:@"redPacketCell" configuration:^(id cell) {
            
        }];
    }
    // 商品
    else if (indexPath.section == 5) {
        return (SCREEN_WIDTH - 20) / 2 + 40;
    }
    
    
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section >= 2 && section <= 5) {
        return 40;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section >= 2 && section <= 5) {
        
        ByViewHomeIndexSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"sectionHeader"];
        header.tag = section;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchHeader:)]; 
        [header addGestureRecognizer:tap];
        if (section == 2) {
            header.title = @"消费得积分";
        }
        else if (section == 3) {
            header.title = @"服务更实惠";
        }
        else if (section == 4) {
            header.title = @"红包席卷而来";
        }
        else if (section == 5) {
            header.title = @"蜂王推荐";
        }
        return header;
    }
    return UIView.new;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section >= 2 && section <= 4) {

        return 10;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return UIView.new;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:false];

    // 商品
    if (indexPath.section == 5) {
        ByShopProductDetailVC *vc = [ByShopProductDetailVC new];
        [self by_normalPush:vc hasNavi:true];
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offset = scrollView.contentOffset.y;
    
    // 往下拉
    if (offset < 0) {
        self.header.offset = offset;
    }
    // 向上推，要把导航栏的颜色显示
    else {
        CGFloat ratio = offset / 88;
        _naviBarAlpha = MIN(ratio, 0.99);
        _naviBarAlpha = MAX(_naviBarAlpha, 0);
        UIColor *color = [BY_THEME_COLOR colorWithAlphaComponent:_naviBarAlpha];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:color] forBarMetrics:UIBarMetricsDefault];
    }
}


#pragma mark - 未登录先登录
- (BOOL)loginIfOnoff {
    
    if (!USER) {
        ByLoginVC *vc = [ByLoginVC new];
        ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:vc];
        [self presentViewController:navi animated:true completion:nil];
        return false;
    } else {
        return true;
    }
}

#pragma mark - 点击事件
// 定位城市
- (void)cityLocation {
    
    ByLocationCityVC *vc = [ByLocationCityVC new];
    [self by_normalPush:vc hasNavi:true];
    vc.didSelectCity = ^(ByModelLocationCity *model) {
        
        self.cityView.city = model.city;
        // 如果不重新设置的话，底部可点击宽度不对，应该是由于设置时我们的视图自动适应于stackView，stackView第一次就设置好了
        [self addCustomItemviews:@[self.cityView] position:ByNavigationItemPositionModeLeft];
    };
}
// 消息或登录
- (void)rightItemsAction:(NSInteger)rightIndex {
    
    // 消息
    if (USER) {
        
    } else {
        ByLoginVC *vc = [ByLoginVC new];
        ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:vc];
        [self presentViewController:navi animated:true completion:nil];
    }
}
// 点击了分类板块
- (void)touchClassPart:(NSInteger)index {
    
    [self by_normalPush:[ByShopVC new] hasNavi:true];

    switch (index) {
        case 0:
            
            break;
        case 1:
            
            break;
        case 2:
            
            break;
        case 3:
            
            break;
        case 4:
            
            break;
        case 5:
            // 商城
//            [self by_normalPush:[ByShopVC new] hasNavi:true];
            break;
        case 6:
            
            break;
        case 7:
            
            break;
        case 8:
            
            break;
        case 9:
            
            break;
            
        default:
            break;
    }
}
- (void)touchHeader:(UITapGestureRecognizer *)tap {
    
    NSInteger section = tap.view.tag;
    if (section == 2) {
        // 消费得积分
        [self by_normalPush:[ByGetScoreFromPayMoreVC new] hasNavi:true];
    }
    if (section == 3) {
        // 服务更优惠
        [self by_normalPush:[ByServiceGoodMoreVC new] hasNavi:true];
    }
    if (section == 4) {
        // 服务更优惠
        [self by_normalPush:[ByRedPacketComeInMoreVC new] hasNavi:true];
    }
    [ByCoreToolAlert showOnlyText:[NSString stringWithFormat:@"%li", section]];
}
@end
